<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        {{$t('route.policy')}}
        <i v-if='false' class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card>
          <basic-table
            tableName='USBRuleGroup'
            ref='USBRuleGroup'
            :pageMethod="(params) => {
              params.search = this.searchValue;
              return $pandaApi.apiGetUsbRuleGroupsByPage(params)
            }"
          >
            <template #table-options="tableSlotData">
              <div class="table-left-options">
                <el-button type="primary" class="icon-button setting-button" style="width: auto;" @click="createUSBRuleGroup">
                  <i class="iconfont iconzhongyiicon_chuangjian" style="font-size: 12px;"></i>
                  <span style="font-size: 12px;">{{$t('policy.NewUSBRuleGroup')}}</span>
                </el-button>
                <el-button class="icon-button setting-button" style="width: auto;"
                 @click="deleteUSBRuleGroup(tableSlotData.table.selectRows, 'USBRuleGroup')" :disabled="loading || tableSlotData.table.selectRows.length <= 0">
                  <i class="iconfont iconzhongyiicon_shanchu" style="font-size: 12px; "></i>
                  <span style="font-size: 12px;">{{$t("policy.DeleteUSBRuleGroup")}}</span>
                </el-button>
                <el-button class="icon-button setting-button" :loading="tableSlotData.table.loading" 
                  @click="$nextTick(()=>tableSlotData.table.refresh().then(()=>{
                    $message.success($t('common.refreshSuccess'))
                  }).catch(()=>{
                    $message.success($t('common.refreshFail'))
                  }))" style="width: auto;margin-right:10px;"
                >
                  <i v-if="!tableSlotData.table.loading" class="el-icon-refresh" style="font-size: 12px; margin-right: 2px;"></i>
                  <span style="font-size: 12px;">{{ $t("common.refresh") }}</span>
                </el-button>
              </div>
            </template>
            <template #table-column="tableSlotData">
              <el-table-column
                type="selection"
                width="40"
                align="center"
								:selectable="(row, index) => {
									if (row.is_default === true) {
										return false;
									}
									return true;
								}"
              ></el-table-column>
              <!-- 名称 -->
              <el-table-column
                prop="name"
                :label="$t('common.name')"
								:formatter="
                  (row, column) => {
                    if (row.name === 'Default USB Rule Group') {
                      return $t('policy.DefaultUSBRuleGroup').toString();
                    } else {
											return row.name;
										}
                  }
                "
                >
              </el-table-column>
              <!-- 租户 -->
              <el-table-column
                v-if="authrole === 'system_admin'"
                prop="cloud_tenant_name"
                :label="$t('common.tenant')"

                >
              </el-table-column>
              <!-- 规则数 -->
              <el-table-column
                prop="resource_name"
                :label="$t('policy.NumberOfRules')"
                >
                <template slot-scope="scope">
                  {{ scope.row.usb_rules.length }}
                </template>
              </el-table-column>
              <!-- 默认USB规则组 -->
              <el-table-column
                :label="$t('policy.DefaultUSBRuleGroup')"
              >
								<template #default="props">
									<el-switch
                    :class="language === 'en' ? 'el-switch-en': ''"
										v-model="props.row.is_default"
										@change="changeDefault(props.row, props.row.is_default)">
									</el-switch>
                </template>
              </el-table-column>
              <!-- 描述 -->
              <el-table-column
                prop="description"
                :label="$t('common.description')"
                >
              </el-table-column>
              <!-- 创建时间 -->
              <el-table-column
                prop="created_at"
                :label="$t('policy.CreationTime')"
                >
								<template #default="props">
                  <span>{{ parseTime(new Date(props.row.created_at)) }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.action')" width="150">
                <!-- 操作 -->
                <template #default="props">
                  <link-button :content="$t('common.delete')" :size="10" :disabled="props.row.is_default === true" :font-size="'12px'" style="margin-right:15px" @click="deleteUSBRuleGroup([props.row], 'USBRuleGroup')" />
                  <link-button :content="$t('policy.ManagementRules')" :size="10" :font-size="'12px'"  @click="$router.push({
                    name: 'USBRule',
                    query: {
                      USBRuleId: props.row.id,
											USBRuleName: props.row.name,
                      tenant_name: props.row.cloud_tenant_name
                    }
                  })" />
                </template>
              </el-table-column>
            </template>
						<template #others-elements="tableSlotData">
							<create-form-dialog @success="tableSlotData.table.refresh" ref="createFormDialog" />
							<delete-form-dialog @success="tableSlotData.table.refresh" ref="deleteFormDialog" />
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import LinkButton from "../../../components/Basic/Button/LinkButton.vue";
import BasicTable from '../../../components/Basic/Table/BasicTable.vue';
import CreateFormDialog from '../components/createUSBRuleGroup.vue';
import DeleteFormDialog from '../components/deleteFormDialog.vue';
import { parseTime, loginTimeslotToString } from '../../../utils';
import { AuthModule } from '../../../store/modules/auth';
import { AppModule } from '../../../store/modules/app';
export default Vue.extend({
  components: {
		CreateFormDialog,
    BasicTable,
    LinkButton,
    DeleteFormDialog,
  },
	computed: {
    parseTime: () => parseTime,
    loginTimeslotToString: () => loginTimeslotToString
  },
  data() {
    return {
      searchValue: '',
      loading: false,
      tenant_options: [],
      language: AppModule.language,
      authrole: AuthModule.authrole
    }
  },
  created() {
    if (AuthModule.authrole === 'system_admin') {
      let tenant_options: any = [];
      (this as any).$tunnyApi.apiGetTenantList().then((res: any) => {
        res.forEach((item: any) => {
          let obj: any = {};
          obj.value = item.id;
          obj.label = item.name
          tenant_options.push(obj);
        });
        this.tenant_options = tenant_options;
      }).catch(() => {
        console.log('tenant-userList-get-error');
      });
    }
  },
  beforeDestroy() {
  },
  methods: {
    createUSBRuleGroup() {
      if (AuthModule.authrole === 'system_admin') {
        let tenant_options: any = [];
        (this as any).$tunnyApi.apiGetTenantList().then((res: any) => {
          res.forEach((item: any) => {
            let obj: any = {};
            obj.value = item.id;
            obj.label = item.name
            tenant_options.push(obj);
          });
          this.tenant_options = tenant_options;
          (this.$refs['createFormDialog'] as any).init(tenant_options);
        }).catch(() => {
          console.log('tenant-userList-get-error');
        });
        return;
      }
      (this.$refs['createFormDialog'] as any).init();
		},
		deleteUSBRuleGroup(data: any, type: string) {
			let obj: any = {};
			obj.data = data;
			obj.type = type;
			(this.$refs['deleteFormDialog'] as any).init(obj);
		},
    getTenantName(id: any) {
      let label = "";
      this.tenant_options.forEach((item: any) => {
        if (item.value == id) {
           label = item.label;
        }
      })
      return label;
    },
    changeDefault(data: any, value: any) {
			this.loading = true;
			(this as any).$pandaApi.apiUpdateUsbRuleGroup(data.id, { is_default: value, cloud_tenant_id: data.cloud_tenant_id }).then((res: any) => {
        console.log(res)
        if(res.error && res.message == '400-错误的请求' || res.error && res.message == "Bad Request") {
          if(res.msg.message.indexOf('not allowed to cancel usb rule group default') != -1){
            this.$message.warning((this as any).$t('policy.message.changeDefaultUSBFail'));
          }
        }else {
          this.$message.success(this.$t('message.requestSuccess').toString())
          this.loading = false;
        }
        (this.$refs['USBRuleGroup'] as any).refresh();
        
			}).catch(() => {
        this.$message.warning(this.$t('message.actionError').toString())
				this.loading = false;
				(this.$refs['USBRuleGroup'] as any).refresh();
			})
		}
  }
})
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #EFF1F4;

  .page-header {
    height: 60px;
    background-color: #FFFFFF;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;
    }
  }

  ::v-deep .el-table .cell {
    overflow: inherit;
  }

  ::v-deep .el-switch__core {
    border-radius: 20px;
  }
}

.table-left-options {
  display: flex;
}

.delete-warning-icon {
  color: #FF931D;
  font-size: 20px;
  margin-right: 10px;

  &::before {
    font-size: 20px;
  }
}
</style>
